﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.API
{

    [Description("API-账户")]
    [ApiAuthentication]
    public class AccountController : BaseApiController
    {
        public IUsersLoginContract UsersLoginContract { set; get; }
        public IUsersContract UsersContract { set; get; }
        public IUsersRolesContract UsersRolesContract { set; get; }
        public IAreaContract AreaContract { get; set; }
        public IAgentCityContract AgentCityContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; }
        public IIntermediaryStaffContract IntermediaryStaffContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public ICityAppMenuContract CityAppMenuContract { get; set; }

        public IUsersLoginLogContract UsersLoginLogContract { get; set; }


        [Description("API-账户-登录")]
        [AllowAnonymous]
        public IHttpActionResult Login([FromBody]LoginParamsModel entity)
        {

            if (entity == null)
            {
                var result = new AjaxResult("传输参数无效", AjaxResultType.Error);
                return Token(result, "");
            }

            var userData = BaseWebApiExt.ApiLogin(UsersLoginContract, entity.LoginName, entity.LoginPass);
            
            if (userData != null && userData.Id != 0)
            {

                var userModel = UsersContract.GetByKey(userData.UserID);
                if (String.IsNullOrEmpty(userModel.Portrait))
                {
                    userModel.Portrait = "";
                }
                var areaModel = AreaContract.GetByKey(userModel.CityID);
                var intermediaryModel = IntermediaryContract.GetByKey(userModel.IntermediaryID);
                var usersRolesModel = UsersRolesContract.Entities.Where(m => m.UserID == userModel.Id && m.IntermediaryRoleID == 1).FirstOrDefault();
                var staffList = (from m in IntermediaryStaffContract.Entities
                                 join n in StaffContract.Entities
                                 on m.StaffID equals n.Id
                                 where m.IntermediaryID == userModel.IntermediaryID
                                 select new {
                                     ModuleID = m.ModuleID,
                                     StaffID = m.StaffID,
                                     Name = n.Name,
                                     Phone = n.Phone,
                                     Sex = n.Sex,
                                     Remark = n.Remark
                                 });//中介业务员集合

                //经纪人角色
                string userRole = usersRolesModel == null ? "" : "店长";

                //版本号
                string versionStr = "1.0.0";
                int versionCode = 1;

                //APP更新地址
                string updateUrl = "";


                List<int> tab = CityAppMenuContract.Entities.Where(p => p.CityID == userModel.CityID).OrderBy(p => p.ShowIndex).Select(p => p.AppMenuID).ToList();


                var result = new AjaxResult("登录成功", AjaxResultType.Success, new { Id = userData.Id, LoginName = userData.LoginName, Name = userModel.Name, Portrait = userModel.Portrait, UserRole = userRole, CityID = areaModel.Id, CityName = areaModel.Name, IntermediaryID = intermediaryModel.Id, IntermediaryName = intermediaryModel.Name, VersionStr = versionStr, VersionCode = versionCode, UpdateUrl = updateUrl, StaffList = staffList.ToList(), Tabs = tab });
                if (String.IsNullOrEmpty(userData.Token))
                {
                    userData.Token = BaseWebApiExt.GetNewToken(UsersLoginContract, userData.Id);//获取新的toekn
                }
                UsersLoginLog ull = new UsersLoginLog();
                ull.IntermediaryID = UsersContract.GetByKey(userData.UserID).IntermediaryID;
                ull.LoginDate = DateTime.Now.ToString("yyyy-MM-dd");
                ull.LoginIP = System.Web.HttpContext.Current.Request.UserHostAddress;
                ull.LoginTime = DateTime.Now;
                ull.UserID = userData.UserID;
                ull.UsersLoginID = userData.Id;
                ull.LoginOs = String.IsNullOrEmpty(entity.OS) ? "IOS" : entity.OS;
                ull.LoginPage = "Main";
                UsersLoginLogContract.Insert(ull);

                return Token(result, BaseWebApiExt.ToCiphertextToken(userData.Token));
            }
            else
            {
                var result = new AjaxResult("用户名或密码错误", AjaxResultType.Error, new { });
                return Token(result, "");
            }
        }

        [Description("API-账户-修改密码")]
        public IHttpActionResult UpdateLoginPass([FromBody]LoginParamsModel entity)
        {
            if (entity == null)
            {
                var result = new AjaxResult("传输参数无效", AjaxResultType.Error);
                return Token(result, "");
            }

            var userData = UsersLoginContract.GetByKey(entity.Id);

            if (userData == null)
            {
                var result = new AjaxResult("没有找到用户", AjaxResultType.Error);
                return Token(result, "");
            }
            if (userData.LoginPass != entity.OldPassWord)
            {
                var result = new AjaxResult("原密码错误", AjaxResultType.Error);
                return Token(result, "");
            }
            else if (entity.OldPassWord == entity.ResPassWord)
            {
                var result = new AjaxResult("两次密码输入不一致", AjaxResultType.Error);
                return Token(result, "");
            }
            else
            {
                UsersLoginContract.UpdateDirect(d => userData.Id == d.Id, d => new UsersLogin { LoginPass = entity.LoginPass });

                var result = new AjaxResult("成功", AjaxResultType.Success, userData);
                return Token(result, "tommyheng123");
            }
        }


        [Description("API-账户-切换城市")]
        public IHttpActionResult ModifyCity([FromBody]ModifyParamsModel entity)
        {
            if (entity == null)
            {
                var result1= new AjaxResult("传输参数无效", AjaxResultType.Error);
                return Token(result1, "");
            }

            var userData = UsersContract.GetByKey(BaseWebApiExt.GetUserIDByToken());
            if (userData == null)
            {
                var result1 = new AjaxResult("没有找到用户", AjaxResultType.Error);
                return Token(result1, "");
            }
            userData.CityID = entity.CityID;
            int count = UsersContract.Update(userData);
            List<int> tab = CityAppMenuContract.Entities.Where(p => p.CityID == entity.CityID).OrderBy(p => p.ShowIndex).Select(p => p.AppMenuID).ToList();
            var result = new AjaxResult("成功", AjaxResultType.Success, new { CityID = entity.CityID, CityName = AreaContract.GetByKey(entity.CityID).Name, Tabs = tab });
            return Token(result, "tommyheng123");
        }
        [Description("API-账户-获得城市列表")]
        public IHttpActionResult CityList()
        {

            var CityList = from a in AgentCityContract.Entities
                           join b in AreaContract.Entities on a.CityID equals b.Id
                           join c in AreaContract.Entities on b.ParentID equals c.Id
                           where a.State > 0
                           select new CityListModel
                           {
                               CityID = b.Id,
                               CityName = b.Name,
                               ProvinceID = b.ParentID,
                               ProvinceName = c.Name
                           };

            var result = new AjaxResult("成功", AjaxResultType.Success, CityList);
            return Token(result, "tommyheng123");
        }

        [Description("API-账户-添加日志")]
        public IHttpActionResult UpdateLog([FromBody]UsersLoginLog entity)
        {
            if (entity == null)
            {
                var result1 = new AjaxResult("传输参数无效", AjaxResultType.Error);
                return Token(result1, "");
            }

            var userData = UsersContract.GetByKey(BaseWebApiExt.GetUserIDByToken());
            if (userData == null)
            {
                var result1 = new AjaxResult("没有找到用户", AjaxResultType.Error);
                return Token(result1, "");
            }
            entity.IntermediaryID = userData.IntermediaryID;
            entity.LoginDate = DateTime.Now.ToString("yyyy-MM-dd");
            entity.LoginIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            entity.LoginTime = DateTime.Now;
            entity.UserID = userData.Id;
            entity.UsersLoginID = UsersLoginContract.Entities.FirstOrDefault(p => p.UserID == userData.Id).Id;
            UsersLoginLogContract.Insert(entity);
            var result = new AjaxResult("成功", AjaxResultType.Success, "");
            return Token(result, "tommyheng123");
        }


    }
}